package com.itheima.d5_synchronized_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String accountId; //卡号
    private double money; //账户余额
    //加上final的目的：让lock对象在Account对象周期内不会发生变化
    private final Lock lock = new ReentrantLock();

    public Account(String accountId, double money) {
        this.accountId = accountId;
        this.money = money;
    }

    //省略getter、setter方法

    //取钱功能
    public void drawMoney(double money) {
        Thread thread = Thread.currentThread();
        String name = thread.getName();

        try{
            lock.lock(); //获取锁

            if (this.money >= money) { //账户余额充足
                System.out.println(name + "成功取钱" + money + "元");
                this.money -= money;

                System.out.println(1 / 0); //异常，如果产生，则会默认终端向下执行

                System.out.println("账户余额为：" + this.money + "元");
            }else {
                System.out.println(name +"余额不足取款失败～");
            }
        }finally {
            //上面try中的逻辑，不论是正常还是异常结束，都能保证释放锁的执行
            lock.unlock(); //释放锁
        }
    }


    @Override
    public String toString() {
        return "Account{" +
                "accountId='" + accountId + '\'' +
                ", money=" + money +
                '}';
    }
}
